<template>
  <vPage>
    <section class="my-gantt px-4 py-4">
      <div class="mb-2 flex">
        <el-date-picker
          v-model="form.month"
          type="month"
          value-format="YYYY-MM"
          placeholder="请选择月份"
          @change="getDataboard"
        />
        <el-button type="primary" class="ml-2" @click="toggleDate"
          >{{ toggle ? "隐藏" : "显示" }}时间</el-button
        >
        <vButton
          auth="/goods/task/picture/schedule-task"
          type="primary"
          @click="handleScheduleTask"
          >任务安排</vButton
        >
        <div class="flex ml-auto">
          <div class="mr-2" v-for="(item, index) in tabList" :key="index">
            <div
              :class="['w-[10px]', 'h-[10px]', 'inline-block']"
              :style="{ backgroundColor: item.color }"
            ></div>
            {{ item.label }}
          </div>
        </div>
      </div>
      <div id="gantt_here1" class="gantt-container"></div>
    </section>
  </vPage>
  <ComModal ref="ComModalRef" @initForm="initGantt"></ComModal>
  <scheduleTask ref="scheduleTaskRef"></scheduleTask>
</template>

<script setup>
{
  /* <script name="TaskPictureTask-board-mountings" setup> */
}
import {
  reactive,
  toRefs,
  onUnmounted,
  onMounted,
  watchEffect,
  defineExpose,
  inject,
} from "vue";
import { ElMessage } from "element-plus";
import ComModal from "../picture/components/boardComModal.vue";
import { getDataboardList, userTaskInfo } from "../picture/api/index.js";
import {
  getCurrentDayNumber,
  getFirstDayOfMonthString,
  getLastDayOfMonthString,
  formatDate,
} from "@/utils/index.js";
import scheduleTask from "../picture/components/scheduleTask";

const gantt = inject("ganttInstance");

const colorMap = new Map([
  [0, "#EAF3FF"],
  [1, "#FAAD14"],
  [2, "#C800AA"],
  [3, "#BCD000"],
  [4, "#00ACC8"],
  [5, "#E50113"],
  [6, "#3487FF"],
  [7, "#CCCCCC"],
  [8, "#67C23A"],
]);

const data = reactive({
  form: {
    mode: 4,
  },
  toggle: false,
  tabList: [
    {
      label: "待分配人员",
      name: 1,
    },
    {
      label: "待处理",
      name: 2,
    },
    {
      label: "处理中",
      name: 8,
    },
    {
      label: "待设计审核",
      name: 3,
    },
    {
      label: "待运营审核",
      name: 4,
    },
    {
      label: "审核未通过",
      name: 5,
    },
    {
      label: "已完成",
      name: 6,
    },
    {
      label: "已取消",
      name: 7,
    },
  ],
});

const { form, toggle, tabList } = toRefs(data);

const toggleDate = () => {
  toggle.value = !toggle.value;

  initGantt();
};

const disabled = computed(() => {
  return !(window.BTN_AUTH || []).includes("/goods/task/picture/allocateTime");
});

const ComModalRef = ref();

//初始化甘特图
let myEvent = null;
const initGantt = () => {
  gantt.config.min_column_width = 160;
  gantt.config.column_width = 250; // 设置每个单元格的宽度为50像素
  gantt.config.add_column = false; //添加符号
  //时间轴图表中，如果不设置，只有行边框，区分上下的任务，设置之后带有列的边框，整个时间轴变成格子状。
  gantt.config.autofit = false;
  gantt.config.row_height = 46;
  gantt.config.bar_height = 36;
  // gantt.config.fit_tasks = true //自动延长时间刻度，以适应所有显示的任务
  gantt.config.auto_types = false; //将包含子任务的任务转换为项目，将没有子任务的项目转换回任务
  // gantt.config.xml_date = '%Y-%m-%d' //甘特图时间格式
  gantt.config.readonly = disabled.value; //是否只读
  // gantt.config.auto_scheduling = true;
  // gantt.config.order_branch = true;
  // gantt.config.order_branch_free = true;
  gantt.plugins({
    tooltip: true,
    quick_info: false, // 快速信息框
    // multiselect: true,// 激活多任务选择
  });
  gantt.config.show_quick_info = false;
  gantt.config.show_links = false;
  gantt.config.drag_progress = false;
  gantt.templates.lightbox_header = function (start_date, end_date, task) {
    return `<b>${task.task_no}</b>`;
  };
  gantt.templates.tooltip_text = function (start, end, task) {
    if (!task.type) {
      return `
        <div>
            ${task.task_no || ""}<br/>
            SKU : ${task.sku || "--"}<br/>
            处理人备注:${task.handle_remark || "--"}<br/>
        </div>
    `;
    }
  };
  gantt.templates.task_row_class = function (start, end, task) {
    switch (task.type) {
      case 1:
        return "person_bg";
      default:
        return ""; // 默认情况下不应用任何额外的样式
    }
  };
  gantt.templates.grid_row_class = function (start, end, task) {
    switch (task.type) {
      case 1:
        return "person_bg";
      default:
        return ""; // 默认情况下不应用任何额外的样式
    }
  };
  gantt.templates.task_class = function (start, end, task) {
    if (task.type) {
      // 如果是主任务
      return "hidden-task"; // 返回一个隐藏主任务的 CSS 类名
    }
    // 其他情况返回默认的任务 CSS 类名
    return "";
  };

  gantt.config.scales = [
    {
      unit: "day",
      step: 1,
      format: "%m月%d日(星期%D)",
      unit_width: 200,
    },
  ];
  if (toggle.value) {
    const columns = [
      { name: "title", label: "人员/任务名称", tree: true, min_width: 260 },
      { name: "start_date", label: "开始时间", min_width: 100 },
      { name: "end_date", label: "结束时间", min_width: 100 },
      { name: "duration", label: "计划工期" },
    ];
    gantt.config.columns = columns;
  } else {
    const columns = [{ name: "title", label: "人员/任务名称", tree: true, width: 260 }];
    gantt.config.columns = columns;
  }

  gantt.i18n.setLocale("cn"); //设置语言
  gantt.init("gantt_here1"); //初始化

  getDataboard();

  gantt.detachEvent("onBeforeTaskChanged");

  gantt.attachEvent("onTaskClick", function (id, e) {
    const targetElement = e.target || e.srcElement;
    if (targetElement.classList.contains("gantt_tree_icon")) {
      // 如果点击的是展开/折叠图标，则不执行后续操作
      return true;
    }
    var task = gantt.getTask(id);
    if (task?.type) return false;
    ComModalRef.value.open(task);
    // 这里可以执行更多操作，比如显示任务详情
    return true; // 返回 true 表示事件已处理
  });
  gantt.attachEvent("onTaskDblClick", function (id, e) {
    // 不执行任何操作，或者可以执行自定义操作
    // 返回true可以阻止默认行为，返回false将允许默认行为
    return false; // 返回true将禁用双击任务的默认行为
  });

  myEvent = gantt.attachEvent("onBeforeTaskChanged", function (id, e) {
    var task = gantt.getTask(id);
    console.log("Task onBeforeTaskChanged:", task);
    // 这里可以执行更多操作，比如显示任务详情
    handleTaskChange(task);
    return true; // 返回 true 表示事件已处理
  });
};

onMounted(() => {
  form.value.month = getCurrentDayNumber();
  tabList.value.forEach((element) => {
    element.color = colorMap.get(element.name);
  });
  gantt.clearAll();
  initGantt();
});

onUnmounted(() => {
  // gantt.detachEvent(myEvent);
  // gantt.detachEvent("onBeforeTaskChanged");
  gantt.detachAllEvents();
});

const getDataboard = () => {
  getDataboardList(form.value).then((res) => {
    const people_data = res.data.people.map((item) => {
      item.text = item.user_name;
      item.type = 1;
      item.open = true;
      item.start_date = getFirstDayOfMonthString(form.value.month);
      item.end_date = getLastDayOfMonthString(form.value.month);
      item.title = item.user_name;
      return item;
    });
    const task_data = res.data.people_task.map((i) => {
      i.color = colorMap.get(i.status);
      i.start_date = new Date(i.start_date);
      i.end_date = new Date(i.end_date);
      i.old_start_date = formatDate(i.start_date);
      i.old_end_date = formatDate(i.end_date);
      i.sku = i.sku.filter((i) => i).join(",");
      i.task_no = i.text;
      const remark = i.is_emphasis_remark ? i.handle_remark : "";
      i.text = `${i.sku}(${i.status_text}) <br/>${remark}`;
      const is_pid = i.pid ? "(子任务)" : "";
      i.title = `${i.task_no}${is_pid}`;
      const user = people_data.find((j) => j.id == i.parent);
      i.user_id = user?.user_id;
      return i;
    });
    const demoData = people_data.concat(task_data);
    gantt.clearAll();
    gantt.parse({ data: demoData }); //填充数据
  });
};

watchEffect(() => {});
defineExpose({
  ...toRefs(data),
});

const handleTaskChange = async (task) => {
  const allot_start_time =
    formatDate(task.start_date).split(" ")?.[0] +
    " " +
    task.old_start_date.split(" ")?.[1];
  const allot_end_time = formatDate(manipulateDate(task.end_date));

  try {
    const res = await userTaskInfo({
      task_id: task.task_id,
      allot_start_time,
      allot_end_time,
      mode: 2,
      user_id: task.user_id,
    });
    ElMessage.success("修改成功");
  } catch (e) {
    throw Error(e);
  }
};

const manipulateDate = (inputDate) => {
  // 将传入的日期字符串转换为时间戳
  var timestamp = Date.parse(inputDate);
  // 减去一秒
  timestamp -= 1000;
  // 将时间戳转换回日期对象
  var modifiedDate = new Date(timestamp);
  // 将日期对象转换为字符串
  var dateString = modifiedDate.toISOString();
  return dateString;
};

// 任务安排
const scheduleTaskRef = ref();
const handleScheduleTask = () => {
  scheduleTaskRef.value.open();
};
</script>
<style scoped lang="scss">
.my-gantt {
  height: calc(100vh - 150px);
  .gantt-container {
    width: 100%;
    height: 100%;
    color: #333;
  }
}
</style>
<style>
.gantt_tree_content {
  color: #333;
}
</style>
